package cn.cumulomq.service;

import java.util.ArrayList;
import java.util.List;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.apache.log4j.Logger;

import cn.cumulomq.MQXMain;
import cn.cumulomq.entity.TeleMessage;
import cn.cumulomq.listener.ReceiveMessageListener;
import cn.cumulomq.parse.ParseManage;
import cn.cumulomq.utils.MessageUtil;

/**
 * 通知上层业务接收报文
 * @author maxuedong
 *
 */
public class ReceiveMessageService implements MessageListener{
	private Logger logger = Logger.getLogger(ReceiveMessageService.class);
	private static List<ReceiveMessageListener> listeners = new ArrayList<ReceiveMessageListener>();
	/**
	 * 添加接收消息的监听
	 * @param listener
	 */
	public void addListener(ReceiveMessageListener listener){
		listeners.add(listener);
	}
	/**
	 * 删除接收消息的监听
	 * @param listener
	 */
	public void removeListener(ReceiveMessageListener listener){
		listeners.remove(listener);
	}
	@Override
	public void onMessage(Message msg) {
		if(listeners.size()==0){
			logger.warn("No message receive listener.");
		}
		if (msg instanceof ObjectMessage) {
			TeleMessage tm = null;
			ObjectMessage om = (ObjectMessage) msg;
            Object body = null;
            try {
                body = om.getObject();
            } catch (JMSException e) {
                logger.error(e);
            }
            if (body instanceof cn.ait.umc.message.Message) {
                cn.ait.umc.message.Message umcMsg = (cn.ait.umc.message.Message) body;
                tm = MessageUtil.createTeleFromUmc(umcMsg);
                tm.setMsgDirection(MessageUtil.MSG_DIRECTION_RECEIVE);
        		ParseManage.getInstance().messageToJson(tm);//解析
        		//根据收电地址存储到不同的数据库
        		String addrs[] = tm.getAddressees().replace("\r\n", " ").split(" ");
        		for(String addr:addrs){
        			if(MQXMain.getInstance().addrEndpointMap.containsKey(addr)){
        				TeleMessageService teleMessageService = new TeleMessageService(addr);
        				teleMessageService.save(tm);
        			}
        		}
        		//通知监听器
        		for(ReceiveMessageListener rml : listeners){
        			rml.onMessage(tm);
        		}
            }
		}
		
		

	}
}
